package com.jmm.neditor.utils.upload;

import com.aliyun.oss.OSSClient;
import com.jmm.neditor.config.ConfigManager;
import com.jmm.neditor.model.AppInfo;
import com.jmm.neditor.model.BaseState;
import com.jmm.neditor.model.FileType;
import com.jmm.neditor.model.State;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jmm.neditor.utils.PathFormat;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class BinaryUploader {

    public static final State save(HttpServletRequest request,
                                   Map<String, Object> conf) {

        boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = null;
        if (fileMap==null || fileMap.size()<=0) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }
        for (String s : fileMap.keySet()) {
            file = fileMap.get(s);
        }

        try {
//            State storageState = saveLocal(request, file, conf);
            State storageState = saveAliyunOSS(request, file, conf);

            return storageState;
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
        }
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);

        return list.contains(type);
    }

    // 保存本地
    private static State saveLocal(HttpServletRequest request,MultipartFile file,Map<String, Object> conf){
        try {

            String savePath = (String) conf.get("savePath");
            String originFileName = file.getOriginalFilename();
            String suffix = FileType.getSuffixByFilename(originFileName);

            originFileName = originFileName.substring(0,
                    originFileName.length() - suffix.length());
            savePath = savePath + suffix;

            long maxSize = ((Long) conf.get("maxSize")).longValue();

            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
            }

            savePath = PathFormat.parse(savePath, originFileName);

            //modified by Ternence
            String rootPath = ConfigManager.getRootPath(request, conf);
            String physicalPath = rootPath + savePath;


            InputStream is = file.getInputStream();
            State storageState = StorageManager.saveFileByInputStream(is,
                    physicalPath, maxSize);
            is.close();

            if (storageState.isSuccess()) {
                storageState.putInfo("url", PathFormat.format(savePath));
                storageState.putInfo("type", suffix);
                storageState.putInfo("original", originFileName + suffix);
            }

            return storageState;
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
        }
    }
    // 保存aliyun
    private static State saveAliyunOSS(HttpServletRequest request,MultipartFile file,Map<String, Object> conf){
        try {

            String savePath = "csh/neditor/";
            String originFileName = file.getOriginalFilename();
            String suffix = FileType.getSuffixByFilename(originFileName);

            originFileName = originFileName.substring(0,
                    originFileName.length() - suffix.length());

            String url = AliyunOSSUtil.uploadNeditorFile(file, savePath, suffix);

            State storageState = new BaseState(true);
            storageState.putInfo( "size", file.getSize() );
            storageState.putInfo( "title", originFileName );
            if (storageState.isSuccess()) {
                storageState.putInfo("url", url);
                storageState.putInfo("type", suffix);
                storageState.putInfo("original", originFileName + suffix);
            }

            return storageState;
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
        }
    }

}
